import Cookies from 'js-cookie';
import { useEffect, useState } from 'react';
import { Form, Input, SigninFilled, LockFilled, VerificationFilled, Checkbox, getRandomNumber, Button, omit, Toast } from 'esy-ui';
import { encryptionEcbMeans, decryptEcbMeans } from '@/utils';
import { useFormatText, useNavigation } from '@/hooks';
import { postLogin } from '@/services';
import { useUserInfoStore } from '@/mobx';
import { REG_ACCOUNT, REG_PSW } from '@/constants';

const FormItem = Form.Item;

const items = [
  {
    name: 'account',
    placeholder: 'please_account_4_12',
    maxlength: 12,
    prefix: <SigninFilled className='text-lg mr-1' />,
    suffix: null,
  },
  {
    name: 'password',
    placeholder: 'please_password_6_12',
    maxlength: 12,
    prefix: <LockFilled className='text-lg mr-1' />,
    type: 'password',
    suffix: null,
  },
  {
    name: 'verifyCode',
    type: 'number',
    placeholder: 'please_code',
    prefix: <VerificationFilled className='text-lg mr-1' />,
    maxlength: 4,
    suffix: (code, changeCode) => (
      <div className='text-primary text-lg cursor-pointer' onClick={changeCode}>
        {code}
      </div>
    ),
  },
];

// 记住密码的逻辑(在form表单校验通过后调用此方法)
const rememberPwd = (isRemeber: boolean, data: Record<string, any>) => {
  const keys = Object.keys(data);
  if (isRemeber) {
    keys.forEach((key) => {
      if (key === 'password') {
        // 密码字段需要加密后保存到cookies中
        const v = encryptionEcbMeans(data[key]);
        Cookies.set(key, v, { expires: 10 });
      } else {
        Cookies.set(key, data[key], { expires: 10 });
      }
    });
  } else {
    keys.forEach((key) => {
      Cookies.remove(key);
    });
  }
};

function Login() {
  const [form] = Form.useForm();
  const { text } = useFormatText();
  const [vcode, setVcode] = useState(null);
  const navigation = useNavigation();
  const { changeUserInfo } = useUserInfoStore();

  const changeCode = () => {
    setVcode(getRandomNumber(4));
  };

  useEffect(() => {
    changeCode();
  }, []);

  useEffect(() => {
    // 获取cookies保存的账号密码
    const account = Cookies.get('account') || '';
    let password = Cookies.get('password') || '';
    console.warn(account, password, rememberPwd);
    if (account && password) {
      // 对密码做解密操作
      password = decryptEcbMeans(password);
      // 这里是cookies回填form表单的逻辑
      form.setFieldsValue({
        account,
        password,
      });
    }
  }, [form]);

  const onSubmit = () => {
    if (form) {
      form
        .validate()
        .then((values) => {
          postLogin(omit(values, ['remember']))
            .then((res: any) => {
              // 保存到mobx
              changeUserInfo(res.Data);
              // 记住账号密码
              rememberPwd(values.remember, omit(values, ['verifyCode', 'remember']));
              // 登录成功的操作
              navigation('/');
            })
            .catch(() => {
              // 登录失败的操作
              changeCode();
            });
        })
        .catch((err) => {
          Toast.show({ content: `${err?.errorFields[0].message}` });
          changeCode();
        });
    }
  };

  // 表单校验
  const rulesObj = {
    account: [
      {
        validator: (_, value) => {
          if (!value || !REG_ACCOUNT.test(value)) {
            return new Error(text('please_account_4_12'));
          }
          return Promise.resolve();
        },
      },
    ],
    password: [
      {
        validator: (_, value) => {
          if (!value || !REG_PSW.test(value)) {
            return new Error(`${text('please_password_6_12')}`);
          }
          return Promise.resolve();
        },
      },
    ],
    verifyCode: [
      {
        validator: (_, value) => {
          if (!value) {
            return new Error(`${text('please_code')}`);
          }
          if (value !== vcode) {
            return new Error(`${text('code_fail')}`);
          }
          return Promise.resolve();
        },
      },
    ],
  };

  return (
    <Form form={form}>
      {items.map((it) => (
        <FormItem key={it.name} name={it.name} rules={rulesObj[it.name]}>
          <Input
            prefix={it.prefix}
            placeholder={text(it.placeholder)}
            type={(it.type || 'text') as any}
            maxLength={it.maxlength}
            suffix={typeof it.suffix === 'function' ? it.suffix(vcode, changeCode) : it.suffix}
          />
        </FormItem>
      ))}
      <div className='flex items-start justify-between text-split text-sm'>
        <FormItem name='remember' label={text('remember_pwd')}>
          <Checkbox />
        </FormItem>
        <div className='text-error'>{text('forget_pwd')}?</div>
      </div>
      <Button className='w-full rounded' type='primary' onClick={onSubmit}>
        {text('signin')}
      </Button>
    </Form>
  );
}

export default Login;
